package com.polaris.live.ui.me

import android.os.Bundle
import android.text.Editable
import android.text.InputFilter
import android.text.InputFilter.AllCaps
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.polaris.live.adapter.AgencyInviteAdapter
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ImmersionBarBuilder
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.ActivityAgencyInviteBinding
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.translation.R.string
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.me.AgencyInviteModel
import com.polaris.live.widget.avatar.FrameImageUtils

/**
 * 邀请页面，加入公会
 *
 * @author Created by lucas on 2023/10/16 09:56
 * @since 1.0.0
 */
class AgencyInviteActivity : BaseVbActivity<AgencyInviteModel, ActivityAgencyInviteBinding>() {

    private var lastAgencyCode: String? = null
    private var userId: Long? = null

    private val mAdapter by lazy { AgencyInviteAdapter() }

    override fun ImmersionBarBuilder.buildImmersionBar() {
        setTitleBar(mBinding.bvTitle)
        setStatusBarDarkFont(false)
        setNavigationBarDarkFont(false)
        attachImmersionBar {
            transparentNavigationBar()
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.etInviteCode.filters =
            mBinding.etInviteCode.filters + arrayOf<InputFilter>(AllCaps())
        mBinding.inviteRecycler.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context)
        }

        mViewModel.agencyInviteMeList()


        initObserver()
        initListener()
    }

    private fun initListener() {
        mBinding.etInviteCode.addTextChangedListener(object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                if ((s?.length ?: 0) >= 2) {
                    //如果是上一个则直接显示
                    val agencyCode = s.toString()
                    if (agencyCode == lastAgencyCode) {
                        mBinding.btnInvite.isEnabled = true
                    }

                    mViewModel.getInviter(agencyCode)
                } else {
                    mBinding.btnInvite.isEnabled = false
                }
            }
        })

        mBinding.ivUserHead.setOnSingleClickListener {
            userId?.let { it1 ->
                Router.builder(RoutePath.USER_SPACE_ACTIVITY)
                    .withInt("page", UserConst.From.MY)
                    .withLong("userId", it1)
                    .navigation(this)
            }
        }

        mBinding.btnInvite.setOnSingleClickListener {
            mViewModel.joinInviterAgency(mBinding.etInviteCode.text.toString())
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.getItem(position).userBasic
            Router.builder(RoutePath.USER_SPACE_ACTIVITY)
                .withAny("userBasic", item)
                .withLong("userId", item.userId).navigation()
        }
    }

    private fun initObserver() {
        mViewModel.joinAgencyLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mBinding.btnInvite.isEnabled = false
                mBinding.clInvite.visibility = View.INVISIBLE
                if (it.inviteType == null || it.inviteType == 1) {
                    ToastGravity.showGravity(string.you_have_successfully_joined_the_guild)
                }
                mViewModel.agencyInviteMeList()
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }

        mViewModel.agencyUserLiveData.observe(this) { resultState ->
            parseState(resultState, {
                userId = it.userId
                lastAgencyCode = mBinding.etInviteCode.text.toString()
                mBinding.btnInvite.isEnabled = true
                mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(it.avatarFrame))
                mBinding.ivUserHead.setImageUrlMiddle(it.avatar)

                mBinding.ivCountry.setCountry(it.country)
                mBinding.tvUserName.text = it.nickname
                mBinding.tvLanguage.text = it.language
                mBinding.vipView.setVipLevel(it.vipLevel)
                mBinding.tvLevel.setRichCharmBySexLevel(
                    it.sex,
                    it.richs,
                    it.charms
                )

                mBinding.clInvite.visibility = View.VISIBLE
            }, {
                mBinding.clInvite.visibility = View.INVISIBLE
            })
        }

        mViewModel.inviteMeLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.isNotEmpty()) {
                    mBinding.llBottomInvite.visibility = View.VISIBLE
                    mAdapter.setList(it)
                }
            })
        }
    }
}